package com.zyh.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.CompositeMessageConverter;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * websocket配置类
 *
 * @author ZYH
 * @version 1.0
 * @date 2025-03-22
 */

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Bean
    public MessageConverter messageConverter() {
        List<MessageConverter> converters = new ArrayList<>();
        // 必须配置JSON转换器
        converters.add(new MappingJackson2MessageConverter());
        return new CompositeMessageConverter(converters);
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry
                .setApplicationDestinationPrefixes("/app") // 匹配 @MessageMapping
                .enableSimpleBroker("/topic", "/queue", "/user"); // 添加 /user 支持点对点
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 关键配置：添加跨域支持并启用SockJS
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS()
                .setSessionCookieNeeded(false) // 关闭Session依赖
                .setHeartbeatTime(60_000);
    }
}
